<!DOCTYPE html>
<html lang="zh-CN">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/apple-touch-icon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="description" content="安全行业从业者，主要方向PC逆向附带安卓和Linux逆向，时不时喜欢写点BUG代码">
  <meta name="author" content="Cray">
  <meta name="keywords" content="">
  <title>SEH创建与查找 ~ 逆向安全博客</title>

  <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/5.12.1/css/all.min.css"  >
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css"  >
<link rel="stylesheet" href="https://cdn.staticfile.org/mdbootstrap/4.13.0/css/mdb.min.css"  >
<link rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/3.0.1/github-markdown.min.css"  >

<link rel="stylesheet" href="//at.alicdn.com/t/font_1067060_qzomjdt8bmp.css">



  <link rel="stylesheet" href="/lib/prettify/tomorrow.min.css"  >

<link rel="stylesheet" href="/css/main.css"  >


  <link rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css"  >


<meta name="generator" content="Hexo 5.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">


    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/">首页</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/archives/">归档</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/tags/">标签</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/links/">友链</a>
          </li>
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" false
      style="background: url('https://w.wallhaven.cc/full/5d/wallhaven-5d2p17.jpg') no-repeat center center;
      background-size: cover;">
    
        <div class="full-bg-img">
        <div class="mask rgba-black-light flex-center">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
                SEH创建与查找
              
            </span>

            
              <br>
              

              <p>
                
                  
                  &nbsp;<i class="far fa-chart-bar"></i>
                  <span class="post-count">
                    695 字
                  </span>&nbsp;
                

                
                  
                  &nbsp;<i class="far fa-clock"></i>
                  <span class="post-count">
                      3 分钟
                  </span>&nbsp;
                

                
                  <!-- 不蒜子统计文章PV -->
                  
                  &nbsp;<i class="far fa-eye" aria-hidden="true"></i>&nbsp;
                  <span id="busuanzi_container_page_pv">
                    <span id="busuanzi_value_page_pv"></span> 次
                  </span>&nbsp;
                
              </p>
            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="py-5 z-depth-3" id="board">
        <div class="post-content mx-auto" id="post">
          <div class="markdown-body">
            <p>创建一个SEH处理函数</p>
<pre><code>#include &quot;stdafx.h&quot;
#define WIN32_LEAN_AND_MEAN
#include &lt;windows.h&gt;
#include &lt;stdio.h&gt;
#include &quot;stdlib.h&quot;

DWORD scratch;

EXCEPTION_DISPOSITION exceptHandler(struct _EXCEPTION_RECORD *ExceptionRecord,
                        void * EstablisherFrame,
                        struct _CONTEXT *ContextRecord,
                        void * DispatcherContext)
&#123;

    unsigned i;

    MessageBox(0,_T(&quot;i am in except!!!&quot;),0,0);

    ContextRecord-&gt;Eax = (DWORD)&amp;scratch;//将eax的值修改为一个全局变量的地址，就可以写入了

    //printf(&quot;%08X \n &quot;, ContextRecord-&gt;Eip);//0x4114c5

    ContextRecord-&gt;Eip += 0x2A;//这里修改的EIP，等于修改恢复异常后下一要执行的语句

    return ExceptionContinueExecution;//这是异常处理的返回结果，让程序返回执行ContextRecord-&gt;Eip的代码
&#125;
int main()
&#123;
    __asm
    &#123;
        push exceptHandler // handler函数的地址
        push FS:[0] // 保存上一级的SEH链地址
        mov FS:[0],ESP // 安装新的EXECEPTION_REGISTRATION结构
    &#125;
    __asm
    &#123;
        mov eax, 0     // 将EAX清零
        mov[eax], 1 // 向0地址写入，会产生访问异常
    &#125;
    printf(&quot;Yes you right!!!\n&quot;);
    __asm
    &#123;
        mov    eax, [ESP]    // 获取前一个结构
        mov FS:[0], EAX // 恢复之前的链
        add esp, 8       // 恢复堆栈
    &#125;
    return 0;

    printf(&quot;Hello Cray\n&quot;);
    exit(0);
&#125;</code></pre>
<p><img src="D:\git笔记\source_posts\20190826" srcset="/img/loading.gif"></p>
<p>Wingdb 调试如图断下，地址访问异常</p>
<p>我来看看在内存中的什么位置</p>
<p>因为SHE链在线程环境块结构偏移为0的地方</p>
<pre><code>0:000&gt; !teb
TEB at 7ffdf000
    ExceptionList:        0012fe4c
    StackBase:            00130000
    StackLimit:           0012e000
    SubSystemTib:         00000000
    FiberData:            00001e00
    ArbitraryUserPointer: 00000000
    Self:                 7ffdf000
    EnvironmentPointer:   00000000
    ClientId:             000026a8 . 0000275c
    RpcHandle:            00000000
    Tls Storage:          7ffdf02c
    PEB Address:          7ffd9000
    LastErrorValue:       0
    LastStatusValue:      c0000139
    Count Owned Locks:    0
    HardErrorMode:        0</code></pre>
<p>查看teb结构地址。接下来我们将这个地址与TEB结构对应</p>
<pre><code>0:000&gt; dt _teb 7ffdf000 .
ntdll!_TEB
   +0x000 NtTib            : 
      +0x000 ExceptionList    : 0x0012fe4c _EXCEPTION_REGISTRATION_RECORD
      +0x004 StackBase        : 0x00130000 Void
      +0x008 StackLimit       : 0x0012e000 Void
      +0x00c SubSystemTib     : (null) 
      +0x010 FiberData        : 0x00001e00 Void
      +0x010 Version          : 0x1e00
      +0x014 ArbitraryUserPointer : (null) 
      +0x018 Self             : 0x7ffdf000 _NT_TIB
   +0x01c EnvironmentPointer : 
   +0x020 ClientId         : 
      +0x000 UniqueProcess    : 0x000026a8 Void
      +0x004 UniqueThread     : 0x0000275c Void
   +0x028 ActiveRpcHandle  : 
   +0x02c ThreadLocalStoragePointer : 
   +0x030 ProcessEnvironmentBlock : </code></pre>
<p>可以看到<code>_EXCEPTION_REGISTRATION_RECORD </code> 结构的地址为</p>
<p>0x0012fe4c </p>
<pre><code class="0:000&gt;">Exceptions1!_EXCEPTION_REGISTRATION_RECORD
   +0x000 Next             : 0x0012ff70 _EXCEPTION_REGISTRATION_RECORD
   +0x004 Handler          : 0x004110a0     _EXCEPTION_DISPOSITION  Exceptions1!ILT+155(?_except_handler1YAKPAU_EXCEPTION_RECORDPAXPAU_CONTEXT+0</code></pre>
<p>Next指向下一个处理函数，Handler指向当前SHE的处理函数</p>
<pre><code>0:000&gt; u 0x004110a0     
Exceptions1!ILT+155(?_except_handler1YAKPAU_EXCEPTION_RECORDPAXPAU_CONTEXT:
004110a0 e91b030000      jmp     Exceptions1!_except_handler1 (004113c0)
Exceptions1!ILT+160(__initterm):
004110a5 e984220000      jmp     Exceptions1!initterm (0041332e)
Exceptions1!ILT+165(___crtTerminateProcess):
004110aa e9cd220000      jmp     Exceptions1!_crtTerminateProcess (0041337c)
Exceptions1!ILT+170(___report_securityfailure):
004110af e99c0d0000      jmp     Exceptions1!__report_securityfailure (00411e50)
Exceptions1!ILT+175(___atonexitinit):
004110b4 e9271f0000      jmp     Exceptions1!__atonexitinit (00412fe0)
Exceptions1!ILT+180(__RTC_UninitUse):
004110b9 e962180000      jmp     Exceptions1!_RTC_UninitUse (00412920)
Exceptions1!ILT+185(___report_securityfailureEx):
004110be e99d0e0000      jmp     Exceptions1!__report_securityfailureEx (00411f60)
Exceptions1!ILT+190(__RTC_Shutdown):
004110c3 e9d8060000      jmp     Exceptions1!_RTC_Shutdown (004117a0)</code></pre>
<p>我们看汇编代码，看看具体SHE的实现，因为我是debug版本的程序，所以由上面的跳转</p>
<pre><code>0:000&gt; u 4113c0 .
004113c0 55              push    ebp
004113c1 8bec            mov     ebp,esp
004113c3 81eccc000000    sub     esp,0CCh
004113c9 53              push    ebx
004113ca 56              push    esi
004113cb 57              push    edi
004113cc 8dbd34ffffff    lea     edi,[ebp-0CCh]
004113d2 b933000000      mov     ecx,33h
004113d7 b8cccccccc      mov     eax,0CCCCCCCCh
004113dc f3ab            rep stos dword ptr es:[edi]
004113de 8bf4            mov     esi,esp
004113e0 6858584100      push    offset Exceptions1!`string&#39; (00415858)
004113e5 ff1514914100    call    dword ptr [Exceptions1!_imp__printf (00419114)]
004113eb 83c404          add     esp,4
004113ee 3bf4            cmp     esi,esp</code></pre>
<p>这就是我们自己加的SHE处理函数</p>

            <hr>
          </div>
          <br>
          <div>
            <p>
            
              <span>
                <i class="iconfont icon-inbox"></i>
                
                  <a class="hover-with-bg" href="/categories/%E9%80%86%E5%90%91/">逆向</a>
                  &nbsp;
                
              </span>&nbsp;&nbsp;
            
            
              <span>
                <i class="iconfont icon-tag"></i>
                
                  <a class="hover-with-bg" href="/tags/SEH/">SEH</a>
                
                  <a class="hover-with-bg" href="/tags/Windbg/">Windbg</a>
                
              </span>
            
            </p>
            
              <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://zh.wikipedia.org/wiki/Wikipedia:CC_BY-SA_3.0%E5%8D%8F%E8%AE%AE%E6%96%87%E6%9C%AC" rel="nofollow noopener noopener">CC BY-SA 3.0协议</a> 。转载请注明出处！</p>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container">
        <div id="toc">
  <p class="h5"><i class="far fa-list-alt"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>
      </div>
    
  </div>
</div>

<!-- custom -->


<!-- Comments -->
<div class="col-lg-7 mx-auto nopadding-md">
  <div class="container comments mx-auto" id="comments">
    
      <br><br>
      
      
  <div class="disqus" style="width:100%">
    <div id="disqus_thread"></div>
    <script>
      var disqus_config = function () {
        this.page.url = 'http://cve.gitee.io/cve/2019/08/26/SEH创建与查找/';
        this.page.identifier = '/2019/08/26/SEH创建与查找/';
      };
      var oldLoad = window.onload;
      window.onload = function () {
        var d = document, s = d.createElement('script');
        s.type = 'text/javascript';
        s.src = '//' + 'crayon-1' + '.disqus.com/embed.js';
        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);
      };
    </script>
    <noscript>Please enable JavaScript to view the <a target="_blank" href="https://disqus.com/?ref_noscript" rel="nofollow noopener noopener">comments
        powered by Disqus.</a></noscript>
  </div>


    
  </div>
</div>

    
  </main>

  
    <a class="z-depth-1" id="scroll-top-button" href="#" role="button">
      <i class="fa fa-chevron-up scroll-top-arrow" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  <footer class="mt-5">
  <div class="text-center py-3">
    <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><b>Hexo</b></a>
    <i class="iconfont icon-love"></i>
    <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"> <b>Fluid</b></a>
    <br>

    
  
    <!-- 不蒜子统计PV -->
    
    &nbsp;<span id="busuanzi_container_site_pv"></span>总访问量 
          <span id="busuanzi_value_site_pv"></span> 次&nbsp;
  
  
    <!-- 不蒜子统计UV -->
    
    &nbsp;<span id="busuanzi_container_site_uv"></span>总访客数 
            <span id="busuanzi_value_site_uv"></span> 人&nbsp;
  
  <br>



    


    <!-- cnzz Analytics icon -->
    

  </div>
</footer>

<!-- SCRIPTS -->
<script src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script src="https://cdn.staticfile.org/popper.js/1.16.1/umd/popper.min.js" ></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script src="https://cdn.staticfile.org/mdbootstrap/4.13.0/js/mdb.min.js" ></script>
<script src="/js/main.js" ></script>


  <script src="/js/lazyload.js" ></script>



  
  <script src="https://cdn.staticfile.org/tocbot/4.10.0/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var navHeight = $('#navbar').height();
      var toc = $('#toc');
      var main = $('main');
      var tocT = navHeight + (toc.offset().top - main.offset().top);
      var tocLimMin = main.offset().top - navHeight;
      var tocLimMax = $('#comments').offset().top - navHeight;
      $(window).scroll(function () {
        var scroH = document.body.scrollTop + document.documentElement.scrollTop;
        if (tocLimMin <= scroH && scroH <= tocLimMax) {
          toc.css({
            'display': 'block',
            'position': 'fixed',
            'top': tocT,
          });
        } else if (scroH <= tocLimMin) {
          toc.css({
            'position': '',
            'top': '',
          });
        } else if (scroH > tocLimMax) {
          toc.css('display', 'none');
        }
      });
      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '.post-content',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        scrollSmooth: true,
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc > p').css('visibility', 'visible');
      }
    });
  </script>







  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>


<!-- Plugins -->



  <script src="https://cdn.staticfile.org/prettify/188.0.0/prettify.min.js" ></script>
  <script>
    $(document).ready(function () {
      $('pre').addClass('prettyprint  linenums');
      prettyPrint();
    })
  </script>





  <script src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      getSearchFile(path);
      this.onclick = null
    }
  </script>



  <script src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <script>
    $("#post img:not(.no-zoom img, img[no-zoom])").each(
      function () {
        var element = document.createElement("a");
        $(element).attr("data-fancybox", "images");
        $(element).attr("href", $(this).attr("src"));
        $(this).wrap(element);
      }
    );
  </script>












</body>
</html>
